package com.pai4j.message.provider;

import com.pai4j.common.bean.PAIResponseBean;
import com.pai4j.common.bean.PAIResponseBeanUtil;
import com.pai4j.domain.vo.response.subjectaccount.ArticleBaseResponseVO;
import com.pai4j.message.core.provider.AbstractResourceProvider;
import com.pai4j.message.model.ResourceInfo;
import com.pai4j.remote.pgc.SubjectArticleClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;

/**
 * 文章资源提供者
 * 提供专题文章资源信息
 *
 * @author PAI4J Team
 * @date 2025-11-01
 */
@Slf4j
@Component
@ConditionalOnBean(SubjectArticleClient.class)
public class ArticleResourceProvider extends AbstractResourceProvider {

    @Autowired
    private SubjectArticleClient articleClient;

    @Override
    public String getResourceType() {
        return "ARTICLE";
    }

    @Override
    protected ResourceInfo doGetResourceInfo(String resourceId) {
        if (StringUtils.isBlank(resourceId)) {
            return null;
        }

        try {
            Long articleId = Long.parseLong(resourceId);
            PAIResponseBean<ArticleBaseResponseVO> response = articleClient.detail(articleId, false);
            
            if (!PAIResponseBeanUtil.isOk(response) || response.getData() == null) {
                log.warn("获取文章信息失败: articleId={}", articleId);
                return null;
            }

            ArticleBaseResponseVO article = response.getData();
            
            // 构建资源信息
            ResourceInfo.ResourceInfoBuilder builder = ResourceInfo.builder()
                    .resourceId(resourceId)
                    .resourceType("ARTICLE")
                    .title(article.getTitle())
                    .ownerId(article.getAuthor())
                    .authorName(article.getAuthor())
                    .jumpUrl("/article/detail/" + resourceId)
                    .status(String.valueOf(article.getStatus()));

            // 设置封面图
            if (article.getCover() != null) {
                String coverUrl = article.getCover().toString();
                builder.coverImage(coverUrl);
            }

            // 设置摘要
            if (StringUtils.isNotBlank(article.getDescription())) {
                builder.summary(article.getDescription());
            }

            return builder.build();

        } catch (Exception e) {
            log.error("获取文章资源信息异常: resourceId={}, error={}", resourceId, e.getMessage(), e);
            return null;
        }
    }

    @Override
    public int getPriority() {
        return 10; // 高优先级
    }
}

